/**
 * File : ReadEventHandler.java <br/>
 * Author : alexgaoyh <br/>
 * Version : 1.1 <br/>
 * Date : 2017年7月5日 <br/>
 * Modify : <br/>
 * Package Name : com.MutiModule.common.codeing.reactor <br/>
 * Project Name : MutiModule-common <br/>
 * Description : <br/>
 * 
 */

package com.MutiModule.common.codeing.nio.reactor;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
/**
 * ClassName : ReadEventHandler <br/>
 * Function : TODO ADD FUNCTION. <br/>
 * Reason : TODO ADD REASON. <br/>
 * Date : 2017年7月5日 下午1:35:32 <br/>
 * 
 * @author : alexgaoyh <br/>
 * @version : 1.1 <br/>
 * @since : JDK 1.6 <br/>
 * @see
 */

public class ReadEventHandler implements EventHandler {

    private Selector demultiplexer;
    private ByteBuffer inputBuffer = ByteBuffer.allocate(2048);

    public ReadEventHandler(Selector demultiplexer) {
        this.demultiplexer = demultiplexer;
    }

    public void handleEvent(SelectionKey handle) throws Exception {
        System.out.println("=====ReadEventHandler.java Read Event Handler =====");

        SocketChannel socketChannel =
                (SocketChannel) handle.channel();

        socketChannel.read(inputBuffer); // Read data from client

        inputBuffer.flip();
        // Rewind the buffer to start reading from the beginning

        byte[] buffer = new byte[inputBuffer.limit()];
        inputBuffer.get(buffer);

        System.out.println("Received message from client : " +
                new String(buffer));
        inputBuffer.flip();
        // Rewind the buffer to start reading from the beginning
        // Register the interest for writable readiness event for
        // this channel in order to echo back the message

        socketChannel.register(
                demultiplexer, SelectionKey.OP_WRITE, inputBuffer);

    }
}